package club.dmyang.alipaydemo.controller;

import club.dmyang.alipaydemo.common.constant.AlipayConstant;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/alipay")
public class AlipayController {

    /**
     *
     * @param order_id 订单号
     * @param order_amount 金额
     * @param subject 商品说明
     */
    @RequestMapping("/pay")
    public void pay(HttpServletRequest httpRequest,
                    HttpServletResponse httpResponse,
                    String order_id, String order_amount, String subject) throws IOException {
        // 创建Alipay客户端
        AlipayClient alipayClient = new
                DefaultAlipayClient(AlipayConstant.serverUrl,AlipayConstant.appId,
                AlipayConstant.privateKey,AlipayConstant.format,AlipayConstant.charset,
                AlipayConstant.alipayPulicKey,AlipayConstant.signType );


        //创建API对应的request
        AlipayTradeWapPayRequest alipayTradeWapPayRequest = new AlipayTradeWapPayRequest();
        //在公共参数中设置回跳和通知地址
        alipayTradeWapPayRequest.setReturnUrl(AlipayConstant.return_url);
        alipayTradeWapPayRequest.setNotifyUrl(AlipayConstant.notify_url);
        AlipayTradeWapPayModel wapPayModel = new AlipayTradeWapPayModel();
        alipayTradeWapPayRequest.setBizModel(wapPayModel);

        //订单号
        wapPayModel.setOutTradeNo(order_id);
        //金额
        wapPayModel.setTotalAmount(order_amount);
        //商品名称
        wapPayModel.setSubject(subject);
        //商品详细说明，可为空
        wapPayModel.setBody("小米Mix2s，高通845，AI双摄，只需3599，赶快下手吧~");
        //配置支付模式为：WAP支付
        wapPayModel.setProductCode("QUICK_WAP_PAY");

        String form="";
        try {
            form = alipayClient.pageExecute(alipayTradeWapPayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + AlipayConstant.charset);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


/*
通知的map中的内容如下：
gmt_create : 2019-03-09 12:57:17
charset : utf-8
seller_email : ssfhlk6910@sandbox.com
subject : iphone xs max
sign : qK8LQREL6ufsV68AFapRaAgKow1NY9q4SU7KssShiv/9bhs9+Q69HF/dcNTZhkwuhFZ5k2yszrMl9zb5AAnV1+92sJpQY2DgORX+mQ7uz+XyPM+9PzytEPAMspGcjRNAz6Dx5mYA+ZZIp+9lu6yJB5AiyoS0+TXbOO5Vu5pxTyTREAoQDVua7sek97p+95z7Siz4IUyaWudc72plQwTGc/c12UwElrvvVSCsziQKY4GuX6GFmY1lQ1E70WxQuSEnGHyNZHCi/ZFE7CifkUYbO8sI3qQ1ge/8Os4fb0uyVpDd7ZJEYTY4n2CFZFK/KH3CXYVBf/okqjD1R04fVCrFKw==
body : 小米Mix2s，高通845，AI双摄，只需3599，赶快下手吧~
buyer_id : 2088102177676304
invoice_amount : 9999.00
notify_id : 700e34d6093dd09ac5d83a7269cc701ibh
fund_bill_list : [{"amount":"9999.00","fundChannel":"ALIPAYACCOUNT"}]
notify_type : trade_status_sync
trade_status : TRADE_SUCCESS
receipt_amount : 9999.00
app_id : 2016092500596744
buyer_pay_amount : 9999.00
sign_type : RSA2
seller_id : 2088102177275624
gmt_payment : 2019-03-09 12:57:17
notify_time : 2019-03-09 12:57:18
version : 1.0
out_trade_no : 4
total_amount : 9999.00
trade_no : 2019030922001476300500544676
auth_app_id : 2016092500596744
buyer_logon_id : wfd***@sandbox.com
point_amount : 0.00
 */
    /**
     * 此接口需要公网可以访问到，所以开发时需要 内网穿透
     * 支付成功后，支付宝的回调接口
     *  退款、交易关闭、下订单（未支付）、下订单（已支付）、都会有通知的~
     */
    @RequestMapping("/notify")
    public void alipay_notify(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException {
        System.out.println();
        System.out.println("===============================================================");
        System.out.println();
        Map<String, String[]> parameterMap = request.getParameterMap();

        Map<String, String> paramsMap = new HashMap<>(); //将异步通知中收到的所有参数都存放到map中

        //从Map<String, String[]>转为想要的Map<String, String> paramsMap
        parameterMap.forEach( (k, v) -> {
            if (v != null){
                paramsMap.put(k,v[0]);
                System.out.println(k + " : " + v[0]);
            }

        });

        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, AlipayConstant.alipayPulicKey, AlipayConstant.charset, AlipayConstant.signType); //调用SDK验证签名
        if(signVerified){
            System.out.println("校验成功");
            System.out.println("支付状态为：" + paramsMap.get("trade_status"));

        // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
        }else{
            System.out.println("校验失败");
        // TODO 验签失败则记录异常日志，并在response中返回failure.
        }
    }
}
